'''
Created on 2014-2-5

@author: apple
'''
from com.ad.sword.web.common import *
from com.ad.sword.dao.models import Role


@tojson
@check_required_argument
def list(request):
    roles = string_ifilter(request, Role.objects, ["name"])
    roles = sort(request, roles)
    page_no = int(request.REQUEST.get("page_no", 0))
    page_size = int(request.REQUEST.get("page_size", 40))

    list = {"items": [], "page_size": page_size, "page_no": page_no, "count": roles.count()}
    roles=roles.skip(page_no * page_size).limit( page_size)
    for k in roles:
        r={}
        r[k]=roles[k]
        list['items'].append(r)

    return list

@tojson
@check_required_argument
def delete(request):
    ids = get_required_argument(request, "id").split(',')
    for id in ids:
        role=Role.objects.get(id=id)
        role.delete()
    return message(_("OK"))



@tojson
@check_required_argument
def add(request):
    from django.db import IntegrityError

    role = Role()
    role.name = get_required_argument(request, "name")
    role.description = request.REQUEST.get("description", '')
    
    
    try:
        role.save()
    except IntegrityError:
        return error_msg(msg = _("name %s already exist")% role.name)
    request.log.Info(title=_("Add Role"),description=_("Add role %s") % role.name);
    return message("OK")


@tojson
@check_login
@check_permission("Administrator")
def edit(request):
    from django.db import IntegrityError

    id = get_required_argument(request, "id")
    try:
        role = Role.objects.get(id=id)
    except DoesNotExist:
        return error_msg(msg=_("Role does not exist"))
    
    if request.REQUEST.get('name', None):
        role.name = request.REQUEST['name']
        
    if request.REQUEST.get('description', None):
        role.description = request.REQUEST["description"]

    if request.REQUEST.get('feature_ids', None):
        feature_ids = request.REQUEST["feature_ids"]


    try:
        role.save()
    except IntegrityError:
        return error_msg(msg = _("Role name %s already exist") % role.name)
    request.log.Info(title=_("Edit role"),description=_("Edit user %s") % role.name);
    return message(_("OK"))